<template>
	  <div class="page_root">
	    <!-- searchForm 部分 -->
	    <search-form
	      :search-setting="searchFormState.searchFieldList"
	      :data-source-id="searchFormState.dataSourceId"
	      :get-page-column-value="getPageColumnValueApi"
	      back-color="#FFFFFF"
	      name-place="horizontal"
	      show-reset
	      show-search
	      @searchForm="handleSearch"
	    />

	    <!-- 按钮组部分 -->
	    <div class="button-content">
	      <div class="button-list">
	        <p class="table_title"> 基础数据字典管理 </p>
	        <operate-button
	          :button-list="computedButtonGroupList"
	          :max-show="2"
	          :form-id="50000753"
	          :page-data="currentPageInfo"
	          :get-export-template="getExportTemplateApi"
	          :export-by-templateId="exportByTemplateIdApi"
	          :download-excel="downloadExcel"
	          :filter="filterCondition"
	          @action="handleClickGlobalAction"
	        />
	      </div>
	    </div>

	    <custom-table-column :isCustomColumn="false" :plainOptions="tableState.columns" @filter="handleFilterColumn" />

	    <!-- 表格部分 -->
	    <div class="table-content">
	      <a-table
	        :class="{ 'pagination-table': !!tableState.pagination}"
	        :bordered="false"
	        :columns="getTableColumns"
	        :data-source="tableState.dataSource"
	        :scroll="tableScroll()"
	        :pagination="tableState.pagination"
	        :custom-row="getTableCustomRow"
	        row-key="id"
	        :row-selection=" false ? { selectedRowKeys: tableState.selectedRowKeys, onChange: handleSelectTableRow } : null"
	        @change="handleTableChange"
	      >
	        <template #headerCell="{ title,column }">
	          <span :style="textStyle(column.displayInfo?.text?.titleStyle)" class="display-block">
	            {{title}}
	          </span>
	        </template>
	        <template #bodyCell="{ text, column, record, index }">
	          <template v-if="column.dataIndex === 'sequenceNumber'">
	            <span class="display-block sequence-number-text-style">
	              {{ index + 1 }}
	            </span>
	          </template>
	          <template v-else-if="column.dataIndex === 'operation'">
	            <operate-button :buttonList="tableState.operatorButtonList" :max-show="2" @action="(actionType) => handleClickOperationButton(record, actionType)" />
	          </template>
	          <template v-else>
	            <format-table-column :column="column" :record="record" :text="text" :index="index" />
	          </template>
	        </template>
	      </a-table>
	    </div>

	    <!-- 新增弹窗 -->
	    <a-modal v-model:visible="formModalState.showAddModal" class="form-model-dialog" width="800px" :footer="null" :mask-closable="false" destroy-on-close>
	      <div style="height:1000px;">
	        <add-form editType="create" class="form-model-dialog" @saveSuccess="handleSaveSuccess('showAddModal')" />
	      </div>
	    </a-modal>

	    <!-- 编辑弹窗 -->
	    <a-modal v-model:visible="formModalState.showEditModal" width="800px" :footer="null" :mask-closable="false" destroy-on-close>
	      <div style="height:1000px">
	        <edit-form editType="edit" :id="formModalState.currentRecordId" class="form-model-dialog" @saveSuccess="handleSaveSuccess('showEditModal')" />
	      </div>
	    </a-modal>

	    <!-- 详情弹窗 -->
	    <a-modal v-model:visible="formModalState.showDetailModal" width="800px" :footer="null" :mask-closable="false" destroy-on-close>
	      <div>
	        <detail-form editType="detail" width="800px" class="form-model-dialog" :id="formModalState.currentRecordId" />
	      </div>
	    </a-modal>

	    <batch-export
	      ref="formExport"
	      :filter="filterCondition"
	      :page-data="tableState.pagination"
	      :page-id="50000753"
	      file-name="基础数据字典管理"
	      :columns="tableState.columns"
	      :exportFormList="exportFormListApi"
	      :downloadExcel="downloadExcel"
	    />

	    <a-modal :visible="showImport" title="导入Excel数据" width="700px" @ok="handleImportOk" @cancel="handleImportCancel">
	      <form-import
	        ref="uploadFile"
	        :columns="tableState.columns"
	        page-id="50000753"
	        data-source-name="基础数据字典管理"
	        :downloadExcel="downloadExcel"
	        :downImportTemplate="downImportTemplateApi"
	        @changeUpload="handleChangeUpload"
	      />
	    </a-modal>

	    <a-drawer
	      v-if="templateManageVisible"
	      :visible="templateManageVisible"
	      placement="bottom"
	      height="100%"
	      mask-closable="false"
	      keyboard="false"
	      destroy-on-close="true"
	      @close="closeTemplateManageVisible"
	    >
	      <template-manage
	        :colum-list="tableState.columns"
	        :pageId="50000753"
	        :addExportTemplate="addExportTemplateApi"
	        :deleteExportTemplate="deleteExportTemplateApi"
	        :getExportTemplate="getExportTemplateApi"
	        :applicationId="50000005"
	      />
	    </a-drawer>
	  </div>
	</template>
	<script setup>
	  
import {
  h, ref, reactive, toRaw, markRaw, watch, computed,
  onBeforeMount, onMounted, onBeforeUnmount, onUnmounted, onActivated, onDeactivated
} from "vue";
import { useRoute, useRouter } from 'vue-router';
const router = useRouter();
const route = useRoute();
import { get, post, put, del, request } from '@/utils/http/Axios';
import { cloneDeep, isNullOrEmpty, isEmptyArr, isNullOrUnDef, localGet, isContained, isArray, isEmpty, merge, getDifferenceArray, isObject, traversalTreeStructure, checkCaseCondition } from '@/utils/index';
import dayjs from 'dayjs';
import weekday from 'dayjs/plugin/weekday';
import weekOfYear from 'dayjs/plugin/weekOfYear';
import LocaleData from 'dayjs/plugin/localeData';
dayjs.extend(weekday);
dayjs.extend(weekOfYear);
dayjs.extend(LocaleData);
import { getPagePcChartsDataSourceConvert } from '@/utils/chart';

import { message, notification, Modal } from 'ant-design-vue'

import SearchForm from '@/components/table/SearchForm.vue';
import OperateButton from '@/components/table/OperateButton.vue';
import BatchExport from '@/components/table/BatchExport.vue';
import FormImport from '@/components/table/FormImport.vue';
import FormatTableColumn from '@/components/table/FormatTableColumn.vue';
import TemplateManage from '@/components/table/templateManage.vue'

// 表格管理的表单组件
import AddForm from '@/views/form/Form50000753.vue';
import EditForm from '@/views/form/Form50000753.vue';
import DetailForm from '@/views/form/Form50000753.vue';
// 组件基本数据
const applicationId = 50000005;

// ---------------------------- api接口部分 ----------------------------

    function getRequestByParam(config){
        return request({
          ...config,
          timeout: 360000,
          headers: {
            'Content-Type': 'application/json',
          },
        });
    }

    // 获取表格数据
    function fetchDataSourceApi(params) {
      return post('/taishan-runtime/api/v4/page_data/search', params)
    }
    // 表格支持树形数据接口
    function fetchTreeFormList(data) {
      return post('/taishan-runtime/api/v4/page_data/tree', data);
    }

    // 删除表格数据
    function deleteDataSourceItemApi(pageDataIdList) {
      const params = {
        processInstanceName: '基础数据字典管理',
        applicationId,
        triggerAction: 'DELETE',
        pageId: 50000753,
        bodyConfig: [],
        pageDataIdList
      };
      return del('/taishan-runtime/api/v4/page_data', { data: params });
    }

    // 获取搜索字段选项数据
    function getPageColumnValueApi(params) {
      return post('/taishan-runtime/api/v3/page_data/column/value', params);
    }

    // 导出表单数据列表
    function exportFormListApi(data) {
      return getRequestByParam({ url: '/taishan-runtime/api/v3/page_data/export',method:'POST',responseType:'arraybuffer', data });
    }

    // 下载模板
    function downImportTemplateApi(pageId) {
      return getRequestByParam({url: '/taishan-runtime/api/v4/page_data/download/template/50000753',method:'GET' ,responseType:'blob' });
    }

    // 文件上传
    function importDataApi(data) {
      return getRequestByParam({ url: '/taishan-runtime/api/v4/page_data/import',method:'POST',responseType:'blob', data });
    }

    // 表单数据导出模板管理列表
    function getExportTemplateApi(data) {
      return post('/taishan-runtime/api/v1/page_data/export_template/search', data);
    }

    // 删除导出模板
    function deleteExportTemplateApi(data) {
      return del('/taishan-runtime/api/v1/page_data/export_template', data);
    }

    // 新增导出模板
    function addExportTemplateApi(data) {
      return post('/taishan-runtime/api/v1/page_data/export_template', data);
    }

    // 根据模板导出表单数据
    function exportByTemplateIdApi(templateId, data) {
      return getRequestByParam({url: `/taishan-runtime/api/v1/page_data/export_template/${templateId}`,method:'POST' ,responseType:'arraybuffer',data});
    }

    // 添加自定义列
    function editColumnList(data) {
      return put('/taishan-runtime/api/v1/low_code/table_design/custom/column', data);
    }
    // 查询自定义列
    function getColumnList(id) {
      return get(`/taishan-runtime/api/v1/low_code/table_design/custom/column/${id}`);
    }


// ============================ api接口部分 ============================

// ---------------------------- searchForm 相关 ----------------------------

const searchFormState = reactive({
  searchFieldList: [],
  dataSourceId: 50000753,
  formData: {}
});

// 将搜索字段的描述信息转换成map结构：key为字段的uid，value为字段的描述信息
const searchFieldMap = computed(() => {
  const searchFieldMap = {};
  searchFormState.searchFieldList.forEach(item => {
    searchFieldMap[item.fieldValue] = item;
  });

  return searchFieldMap;
});

// 根据searchForm的表单数据，生成过滤条件
const filterCondition = computed(() => {
  return generateFilterCondition(searchFormState.formData);
});

// 根据searchForm的数据，生成过滤条件
function generateFilterCondition() {
  const conditionList = [];
  for (const key in searchFormState.formData) {
    const value = searchFormState.formData[key];
    // 如果当前字段有值，则将该字段加到过滤条件中
    if (value || value === 0) {
      conditionList.push({
        expression: {
          filterType: 'CONDITION',
          filterCondition: {
            conditionType: searchFieldMap.value[key].fuzzyMatching  ? 'CONTAIN' : 'EQUALS',
            filterColumnName: key,
            type: searchFieldMap.value[key].fieldType.toUpperCase(),
            value
          }
        }
      });
    }
  }

  if (conditionList.length) {
    return {
      operator: 'AND',
      children: conditionList
    };
  } else {
    return {};
  }
}

function handleSearch(formData) {
  searchFormState.formData = { ...formData };

  // 获取表格数据
  fetchDataSource();
}

// ============================ searchForm 相关 ============================

// ---------------------------- 表格状态 ----------------------------

const tableState = reactive({
  columns: [
    { title: '类型',blocks: {"value":"data_type","componentKey":"antd_select_form_pc"}, dataIndex: 'data_type', displayType: 'text', sorter: false, fixed:'false', displayInfo: {"text":{"contentStyle":{"align":"left","bold":false,"color":"#000000","fontSize":14,"italic":false,"underline":false},"titleStyle":{"align":"left","bold":false,"color":"#000000","fontSize":14,"italic":false,"underline":false}}}, subForm:false, children: [ ] },
    { title: '值',blocks: {"value":"data_value","componentKey":"antd_input_form_pc"}, dataIndex: 'data_value', displayType: 'text', sorter: false, fixed:'false', displayInfo: {"text":{"contentStyle":{"align":"left","bold":false,"color":"#000000","fontSize":14,"italic":false,"underline":false},"titleStyle":{"align":"left","bold":false,"color":"#000000","fontSize":14,"italic":false,"underline":false}}}, subForm:false, children: [ ] },
    { title: '操作', dataIndex: 'operation',fixed:'false' }
  ],
  customColumns:[],
  operatorButtonList: [
    { type: 'edit', buttonType: 'link', buttonName: '编辑' },
    { type: 'details', buttonType: 'link', buttonName: '详情' },
    { type: 'delete', buttonType: 'link', buttonName: '删除',showConfirm:true },
  ],
  dataSource: [],
  pagination: {
    current: 1,
    pageSize: 10,
    total: null,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total, range) => `共${total}个项目，第${tableState.pagination.current}/${Math.ceil(tableState.pagination.total / tableState.pagination.pageSize)}页`,
    position: ['bottomRight'],
  },
  selectedRowKeys: []
});

// 通过handleNode递归处理树形结构、handleLeafNode对叶子节点进行处理。data为需要递归的树结构
const getNodeData = (data, handleNode = () => ({}), handleLeafNode = () => {}) => {
  const filterData = [];
  for (let index = 0; index < data.length; index++) {
    // 创建引用对象，用于过滤叶子节点的实现
    const reference = {};
    reference.node = handleNode(data[index]);
    if (data[index].children && data[index].children.length) {
      // 如果有children继续递归
      const result = getNodeData(data[index].children, handleNode, handleLeafNode);
      if (result.length) {
        reference.node.children = result;
      }
    } else {
      handleLeafNode(data[index], reference);
    }
    reference.node && filterData.push(reference.node);
  }
  return filterData;
};

// 获取表格数据
function fetchDataSource() {
  let pageNo = 1;
  let pageSize = 1000;
  if (tableState.pagination) {
    pageNo = tableState.pagination.current;
    pageSize = tableState.pagination.pageSize;
  }

  const params = {
    filter: {},
    filterCondition: filterCondition.value,
    id: '',
    name: '',
    pageId: 50000753,
    pageNo,
    pageSize,
    parentId: '',
    sort: { id: 'DESC' }
  };
  fetchDataSourceApi(params).then(response => {
    const { dataList = [], columnList = [], totalElements,totalPage } = response.data || {};
    // 子表单的key值
    const subFormList = [...new Set(columnList.filter((item) => item.subForm).map((item) => item.formKey))]
    tableState.dataSource = formatDataList(dataList, subFormList);
    // 获取数据后，过滤一下selectedRowKeys
    updateSelectedRowKeys();
    if(columnList && columnList.length > 0){
      const columnListByPermissions = ['sequenceNumber','operation'].concat(columnList.map(field => field.key));
      tableState.columns = tableState.columns.filter(item=>{
        item.customCell = setCustomCell;
        return columnListByPermissions.includes(item.dataIndex) || (item.subForm && item.children.length > 0 && item.children.some(child => columnListByPermissions.includes(child.dataIndex)));
      });
    }
    // 如果设置了分页，则更新元素的总数
    if (tableState.pagination) {
      tableState.pagination.total = totalElements;
      //当前页数大于总页数（删除时出现）
      if(tableState.pagination.current>totalPage && totalPage>0){ 
        tableState.pagination.current=totalPage;
        fetchDataSource();
      }
    }
  });
}

// 组装格式化表格数据
function formatDataList(dataList, subFormList) {
  const resultDataList = []; // 输出的数据
  dataList.forEach((formData, dataIndex) => {
    const rowInfo = {
      rowSpan: 1,
      rowList: []
    };
    let dataItem = {};
    let subformFieldList = []; // 子表单字段列表

    const additionRowList = []; // 子表单额外增加的列
    //  子表单数据格式化
    Object.keys(formData).forEach(item => {
      // 暂时不对children数据进行处理
      if (item !== 'children') {
        const filedValue = formData[item];
        // 如果是对象，可认为是子表单(地址组件也可能是对象)
        if (isObject(filedValue) && subFormList.includes(item)) {
          const { dataList: subformDataList } = filedValue;
          if (isNullOrEmpty(subformDataList)) {
            return;
          }
          // 获取需要合并的单元的最大值
          subformDataList.length > rowInfo.rowSpan && (rowInfo.rowSpan = subformDataList.length);
          // 遍历数据拆分成表格需要的数据
          subformDataList.forEach((subformDataItem, index) => {
            //  提取出id，避免合并时覆盖掉主数据
            const { id,  ...pureData } = subformDataItem;
            if (index === 0) { // 第一项数据合并到当前的的行中
              // 记录子表单的所有字段，取并集
              subformFieldList = Array.from(new Set(subformFieldList.concat(Object.keys(pureData))));
              merge(dataItem, pureData);
            } else {
              // 其他数据放到新行中
              (isNullOrUnDef(additionRowList[index - 1]) || isEmpty(additionRowList[index - 1])) && (additionRowList[index - 1] = { id: pureData.page_id + "_" + id }); // 新行初始化为一个空对象，id为拼接id，避免重复
              merge(additionRowList[index - 1], pureData);
            }
          });
          dataItem[item] = filedValue;
        } else if (isNullOrUnDef(dataItem[item])) { // dataItem中没有这一个数据，就推进去
          // 需要合并的单元格
          rowInfo.rowList.push(item);
          dataItem[item] = dataItem[item] ? dataItem[item] : filedValue;
        }
      } else {
        dataItem[item] = formData[item];
      }
    });
    // 与子表单中的所有字段取差集，保证没有额外的合并元素
    rowInfo.rowList = getDifferenceArray(rowInfo.rowList, subformFieldList);
    // 处理附加到行合并信息
    dataItem["__ADDITION_ROW_INFO"] = rowInfo;
    // 推入处理完的数据
    resultDataList.push(dataItem);
    // 合并增加额外的列，并附加上额外的信息
    additionRowList.length > 0 && (resultDataList.push(...additionRowList.map(item => {
      item["__ADDITION_ROW_INFO"] = {
        ...rowInfo,
        extra: true
      };
      return item;
    })));
  });
  return resultDataList;
}

// 设置行合并
function setCustomCell(record, rowIndex, column){
  const { rowSpan, rowList, extra } = record.__ADDITION_ROW_INFO || {}
  // 原始单元格合并后，插入进来的行隐藏该单元格
  if(extra && ['sequenceNumber','operation'].concat(rowList).includes(column.dataIndex)){
    return { rowSpan: 0 }
  }
  // 合并单元格
  if(['sequenceNumber','operation'].concat(rowList).includes(column.dataIndex)){
    return { rowSpan: rowSpan }
  }
  return { rowSpan: 1 }
}

// 更新表格的选中行列表
function updateSelectedRowKeys() {
  const allRecordIdMap = {};
  tableState.dataSource?.forEach(item => {
    allRecordIdMap[item.id] = true;
  });

  // 过滤选中行的key：只保留在当前表格数据中存在的行
  tableState.selectedRowKeys = tableState.selectedRowKeys.filter(key => allRecordIdMap[key]);
}

// 初始化时，获取表格数据
fetchDataSource();

// 表格分页发生变化
function handleTableChange(pagination) {
  const { current, pageSize } = pagination;
  tableState.pagination.current = current;
  tableState.pagination.pageSize = pageSize;

  // 重新加载数据
  fetchDataSource();
}

// 选择表格行
function handleSelectTableRow(selectedRowKeys) {
  tableState.selectedRowKeys = selectedRowKeys;
}

function textStyle(item){
  if (!item) {
    return;
  }
  const alignType = {
    ALIGN_LEFT: 'left',
    ALIGN_CENTER: 'center',
    ALIGN_RIGHT: 'right',
  };
  const { fontSize = 14, color = '#000', bold, italic, underline, align = 'ALIGN_LEFT' } = item;
  return {
    fontSize: `${fontSize}px`,
    color,
    textAlign: alignType[align],
    fontWeight: bold ? 'bold' : 'normal',
    textDecoration: underline ? 'underline' : 'none',
    fontStyle: italic ? 'italic' : 'initial',
  };
}

// 操作列不同按钮类型触发点击事件的处理策略
const recordOperationActionStrategy = {
  edit(recordId) {
    formModalState.currentRecordId = recordId;
    formModalState.showEditModal = true;
  },
  details(recordId) {
    formModalState.currentRecordId = recordId;
    formModalState.showDetailModal = true;
  },
  delete(recordId) {
    deleteDataSourceItemApi([recordId]).then(() => {
      // 删除成功后，重新加载数据
      fetchDataSource();
    });
  }
};
//过滤显示自定义列
const getTableColumns = computed( () => {  
  let customColumn = tableState.customColumns.map(item=>{
    return item.key;
  });
  const columns = customColumn.length ? getFilterColumn(tableState.columns,customColumn) : tableState.columns;
  return columns;
})
const getFilterColumn = (columns,filterList) => {
  if(!columns || columns.length <= 0){
    return [];
  }
  return columns.filter(item=>{
    item.children = getFilterColumn(item.children,filterList);
    return ['sequenceNumber','operation'].includes(item.dataIndex) || filterList.includes(item.dataIndex) || item.children.length > 0 || item.subform;
  })
}

// 表格奇偶数 行背景颜色
const getTableCustomRow = (_, index) => {
  const evenLineBackColor='f9f9f9';
  const oddLineBackColor='#FFFFFF';
  return {
    style: {
      'background-color': index % 2 === 1 ? oddLineBackColor : evenLineBackColor,
    },
  };
};

function tableScroll(){
  return {
    
    
    scrollToFirstRowOnChange: false,
  };
};

// 点击操作列的按钮
function handleClickOperationButton(record, actionType) {
  const { id } = record;
  recordOperationActionStrategy[actionType] && recordOperationActionStrategy[actionType](id);
}

onMounted(()=>{
  //加载自定义列
  getColumnList(50000046).then(resp => {
    const { data } = resp;
    tableState.customColumns=data?.columnList || [];
})
})

// ============================ 表格状态 ============================

// ---------------------------- 按钮组部分 ----------------------------

const buttonListConfig = [
  { type: 'add', buttonType: 'primary', buttonName: '新增' },
];
const computedButtonGroupList = computed(() => {
  const selectRowCount = tableState.selectedRowKeys.length;
  return buttonListConfig.map(item => {
    const { type } = item;
    let disabled = false;
    if (type === 'edit' || type === 'details') {
      disabled = selectRowCount !== 1;
    }
    if (type === 'delete') {
      disabled = selectRowCount < 1;
    }
    return {
      ...item,
      disabled
    };
  });
});

// 表格当前的分页信息
const currentPageInfo = computed(() => {
  // 如果表格没有分页，则默认为第一页，1000条
  if (!tableState.pagination) {
    return { current: 1, pageSize: 1000 }
  }

  const { current, pageSize } = tableState.pagination;
  return { current, pageSize };
});

// 按钮组不同按钮类型触发点击事件的处理策略
const globalActionStrategy = {
  add() {
    formModalState.showAddModal = true;
  },

  edit() {
    const [currentRecordId] = tableState.selectedRowKeys;
    formModalState.currentRecordId = currentRecordId;
    formModalState.showEditModal = true;
  },

  details() {
    const [currentRecordId] = tableState.selectedRowKeys;
    formModalState.currentRecordId = currentRecordId;
    formModalState.showDetailModal = true;
  },

  delete() {
    deleteDataSourceItemApi(tableState.selectedRowKeys).then(() => {
      // 删除成功后，重新加载数据
      fetchDataSource();
    });
  },
  export(){
    formExport.value.init();
  },
  import(){
    openImportModal();
  },
  seniorExport(){
    templateManageVisible.value = true;
  }
};

function handleClickGlobalAction(actionType) {
  // 调用当前事件类型对应的处理策略进行处理
  globalActionStrategy[actionType] && globalActionStrategy[actionType]();
}

// ============================ 按钮组部分 ============================

// ---------------------------- 表单弹窗部分 ----------------------------

const formModalState = reactive({
  showAddModal: false,
  showEditModal: false,
  showDetailModal: false,

  // 当前要编辑或显示详情的表格行的id
  currentRecordId: null,
});

function handleSaveSuccess(modalKey) {
  // 关闭弹窗
  formModalState[modalKey] = false;
  // 获取表格数据
  fetchDataSource();
}

// ============================ 表单弹窗部分 ============================

// ---------------------------- 导入弹窗部分 ----------------------------

  const formExport = ref(null);
  /*
 * 下载EXCEL模板
 */
  function downloadExcel(response, name) {
  const blob = new Blob([response], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
  });
  const downloadElement = document.createElement('a');
  const href = window.URL.createObjectURL(blob); // 创建下载的链接
  downloadElement.href = href;
  downloadElement.download = name; // 下载后文件名
  document.body.appendChild(downloadElement);
  downloadElement.click(); // 点击下载
  document.body.removeChild(downloadElement); // 下载完成移除元素
  window.URL.revokeObjectURL(href);
  return href;
}
  
// ============================ 导入弹窗部分 ============================

// ---------------------------- 导出弹窗部分 ----------------------------

    const showImport = ref(false);
    // 打开导入框
    const openImportModal = () => {
      showImport.value = true;
    };
    const handleImportCancel = () => {
      showImport.value = false;
    };

    const importInfo = ref({});
    const handleChangeUpload = (uploadInfo) => {
      importInfo.value = uploadInfo;
    };
    const handleImportOk = () => {
      const { file, importModel, keyField } = importInfo.value;
  
      if (isNullOrEmpty(file)) {
        message.error('请选择上传文件');
        return false;
      }
      if (importModel !== 'ADD' && isEmptyArr(keyField)) {
        message.error('请选择更新关键字段');
        return false;
      }
      const columnList=tableState.columns;
      // 将文件传换成二进制流
      const ids = columnList.map((item) => item.dataIndex);
      const params = {
        pageId: 50000753,
        file,
        importModel,
        keyField: JSON.stringify(
          importModel === 'ADD'
            ? {}
            : {
                pageId: 50000753,
                fieldList: keyField.filter((item) => ids.includes(item)),
                children: getChildrenList(columnList.filter((item) => item.subForm), keyField),
              },
        ),
      };
      fileImport(importDataApi, params).then((res) => {
        const reader = new FileReader();
        reader.readAsText(res);
        reader.onload = function () {
          const result = JSON.parse(reader.result);
          // 判断当前状态
          if (result.status === 'success') {
            message.success('导入成功');
          } else if (result.status === 'failure') {
            message.error(result.errorMsg);
          }
          showImport.value = false;
        };
      });
    };

    function fileImport(fetchApi,params) {
      const formData = new FormData();
      for (const [key, value] of Object.entries(params)) {
        formData.append(key, value);
      }  
      return fetchApi(formData);
    }
  
    const getChildrenList = (list, keyField) => {
      const selectList = []; // 选中的列表
      list.map((item) => {
        if (!isNullOrUnDef(item.children) && !isEmptyArr(item.children)) {
          const pageId=item.children[0].parentId;
          const fieldList=item.children.map(info=>(info.dataIndex)).filter(info=>keyField.includes(info));
          if(!isEmptyArr(item.children)){
            selectList.push({
              pageId: pageId,
              fieldList: fieldList,
            })
          }
        }
      });
      return selectList;
    };
  
// ============================ 导出弹窗部分 ============================

// ---------------------------- 高级模板导出弹窗部分 ----------------------------

    const templateManageVisible = ref(false);
    const closeTemplateManageVisible = () => {
      templateManageVisible.value = false;
    };
  
// ============================ 高级模板导出弹窗部分 ============================

// ---------------------------- 自定义列弹窗部分 ----------------------------

  const handleFilterColumn = (column) => {  
    const params={
        "tableDesignId":50000046,
        "pageId":50000753,
        "columnList":column
    }
    editColumnList(params).then(response => {
      tableState.customColumns = column;
    });
  };
// ============================ 自定义列弹窗部分 ============================
	</script>
	<style lang="less" scoped>
	  
    .page_root {
      height: 100%;
      display: flex;
      padding: 16px 16px;
      flex-direction: column;
      background: #FFFFFF;
    }

    .page_root .table-content {
      flex: 1;
      overflow: auto;
    }

    :deep(.page_root .table-content .tableWrapper-text) {
      display: block;
      text-overflow: ellipsis;
      overflow: hidden;
    }

    :deep(.page_root .table-content .display-block) {
      display: block;
    }

    /** 按钮组部分样式 */
    .page_root .button-content .button-list {
      display: flex;
      justify-content: space-between;
      margin-bottom: 16px;
    }
    .page_root .button-content .button-list .table_title {
      line-height: 32px;
      padding-left: 12px;
      margin-bottom: 0px;
      position: relative;
    }
    .page_root .button-content .button-list .table_title::before {
      position: absolute;
      content: '';
      width: 4px;
      height: 16px;
      top: 8px;
      left: 0px;
      background: #0070cc;
    }

    /** 表格显示分页器时的样式：将分页器置于最底部 */
    .page_root .table-content .pagination-table,
    :deep(.table-content .pagination-table .ant-spin-nested-loading),
    :deep(.table-content .pagination-table .ant-spin-nested-loading .ant-spin-container) {
      height: 100%;
    }
    :deep(.table-content .pagination-table .ant-spin-nested-loading .ant-spin-container .ant-table) {
      height: calc(100% - 64px);
      overflow:auto;
    }
    .display-block{
      display:block;
    }
    .sequence-number-text-style{
      
    }
    .form-model-dialog{
      background:#fff;
    }
	</style>